// import { asyncRouterHandle } from '@/utils/asyncRouter'
import { asyncMenu } from '@/api/api.js'
import { defineStore } from 'pinia'
import { formatRoutesByGG } from '@/utils'
import router from '@/router/index'
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/pinia/modules/user'
// import Cookies from 'js-cookie'

const keepAliveRoutersArr = []

const KeepAliveFilter = routes => {
  routes &&
    routes.forEach(item => {
      // 子菜单中有 keep-alive 的，父菜单也必须 keep-alive，否则无效。这里将子菜单中有 keep-alive 的父菜单也加入。
      if ((item.children && item.children.some(ch => ch.meta.keepAlive)) || item.meta.keepAlive) {
        item.component &&
          item.component().then(val => {
            keepAliveRoutersArr.push(val.default.name)
          })
      }
      if (item.children && item.children.length > 0) {
        KeepAliveFilter(item.children)
      }
    })
}

export const useRouterStore = defineStore(
  'router',
  () => {
    const asyncRouters = ref({
      allRoutes: [],
      leftRoutes: [],
      leftMenus:[]
    })
    const keepAliveRouters = ref(keepAliveRoutersArr)
    const routeMap = {}
    // 从后台获取动态路由
    const SetAsyncRouter = async () => {
      const baseRouter = [
        {
          path: '/layout',
          name: 'layout',
          component: () => import('@/view/layout/index.vue'),
          meta: {
            title: 'layout'
          },
          children: []
        }
      ]
      const baseRouter2 = [
        {
          path: '/layout',
          name: 'layout',
          component: () => import('@/view/layout/index.vue'),
          meta: {
            title: 'layout'
          },
          children: []
        }
      ]
      const errorRoutes = [
        {
          path: '404',
          name: '404',
          hidden: true,
          meta: {
            title: '迷路了*。*',
            closeTab: true
          },
          component: () => import('@/view/error/index.vue')
        },
        {
          path: 'reload',
          name: 'Reload',
          hidden: true,
          meta: {
            title: '',
            closeTab: true
          },
          component: () => import('@/view/error/reload.vue')
        }
      ]
      const asyncRouterRes = await asyncMenu() // 接口获取路由

      if (!asyncRouterRes.succeed) {
        return false
      }
      const userStore = useUserStore()
      const userInfo = userStore.userInfo // 用户信息
      if (asyncRouterRes.data && asyncRouterRes.data.length > 0) {
        const asyncRouter = asyncRouterRes.data
        const formatRoutes = formatRoutesByGG(asyncRouter) // 处理菜单格式
        formatRoutes && formatRoutes.push(...errorRoutes)
        let currentRoutes
        if (userInfo.enterIndex == 1 && ('/' + window.location.hash.split('/')[1]).indexOf('/login') == -1) {
          // 有顶部菜单
          currentRoutes = formatRoutes.filter(r => {
            return r.path === '/' + window.location.hash.split('/')[1]
          })
          // currentRoutes && currentRoutes.push(...errorRoutes)
        } else {
          // 无顶部菜单
          currentRoutes = formatRoutes
        }
        // 筛选当前路由
        baseRouter[0].children = currentRoutes[0].children.length > 0 ? currentRoutes[0].children : [currentRoutes[0]] // 左侧菜单
        baseRouter2[0].children = formatRoutes // 全局菜单

        let emptyObj = {
          path: '/:catchAll(.*)',
          redirect: '/layout/404'
        }
        baseRouter.push(emptyObj)
        baseRouter2.push(emptyObj)
        KeepAliveFilter(formatRoutes)
        asyncRouters.value.leftRoutes = baseRouter
        asyncRouters.value.allRoutes = baseRouter2
        keepAliveRouters.value = keepAliveRoutersArr
        return true
      } else {
        ElMessage({
          showClose: true,
          message: '请联系管理员给该账号分配角色并配置菜单！',
          type: 'error'
        })
        sessionStorage.clear()
        router.push({ name: 'Login', replace: true })
        return true
      }
    }

    return {
      asyncRouters,
      keepAliveRouters,
      SetAsyncRouter,
      routeMap
    }
  },
  // 数据持久化
  {
    persist: {
      enabled: false,
      strategies: [
        { storage: sessionStorage, paths: ['asyncRouters'], key: 'asyncRouters' },
        { storage: sessionStorage, paths: ['asyncRouters2'], key: 'asyncRouters2' }
      ]
    }
  }
)
